package com.ruoyi.project.merchant.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.project.shop.storage.StorageService;
import com.ruoyi.common.utils.FileUtils;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.framework.config.WxPayV3Bean;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.project.merchant.wx.core.kit.PayKit;
import com.ruoyi.project.merchant.wx.core.kit.WxPayKit;
import com.ruoyi.project.merchant.wx.wxpay.WxPayApi;
import com.ruoyi.project.merchant.wx.wxpay.enums.WxApiType;
import com.ruoyi.project.merchant.wx.wxpay.enums.WxDomain;
import com.ruoyi.project.shop.domain.LitemallStorage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

/**
 * Controller
 *
 * @author
 * @date 2020-03-11
 */
@Controller
@RequestMapping("/shop/merchant")
public class MerchantStorageController extends BaseController
{


    @Autowired
    private WxPayV3Bean wxPayV3Bean;

    @Autowired
    private StorageService storageService;

    String serialNo;
    String platSerialNo;

    @RequestMapping("/getSerialNumber")
    @ResponseBody
    public String serialNumber() {
        return getSerialNumber();
    }

    @RequestMapping("/getPlatSerialNumber")
    @ResponseBody
    public String platSerialNumber() {
        return getPlatSerialNumber();
    }

    private String getSerialNumber() {
        if (StrUtil.isEmpty(serialNo)) {
            // 获取证书序列号
            X509Certificate certificate = PayKit.getCertificate(FileUtil.getInputStream(wxPayV3Bean.getCertPath()));
            serialNo = certificate.getSerialNumber().toString(16).toUpperCase();

//            System.out.println("输出证书信息:\n" + certificate.toString());
//            // 输出关键信息，截取部分并进行标记
//            System.out.println("证书序列号:" + certificate.getSerialNumber().toString(16));
//            System.out.println("版本号:" + certificate.getVersion());
//            System.out.println("签发者：" + certificate.getIssuerDN());
//            System.out.println("有效起始日期：" + certificate.getNotBefore());
//            System.out.println("有效终止日期：" + certificate.getNotAfter());
//            System.out.println("主体名：" + certificate.getSubjectDN());
//            System.out.println("签名算法：" + certificate.getSigAlgName());
//            System.out.println("签名：" + certificate.getSignature().toString());
        }
        System.out.println("serialNo:" + serialNo);
        return serialNo;
    }

    private String getPlatSerialNumber() {
        if (StrUtil.isEmpty(platSerialNo)) {
            // 获取平台证书序列号
            X509Certificate certificate = PayKit.getCertificate(FileUtil.getInputStream(wxPayV3Bean.getPlatformCertPath()));
            platSerialNo = certificate.getSerialNumber().toString(16).toUpperCase();
        }
        System.out.println("platSerialNo:" + platSerialNo);
        return platSerialNo;
    }



    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult v3Upload(@RequestParam MultipartFile file) {
        // v3 接口上传文件
        try {
            String originalFilename = file.getOriginalFilename();
            LitemallStorage litemallStorage = null;
            litemallStorage = storageService.store(file.getInputStream(), file.getSize(),
                    file.getContentType(), originalFilename);
            File mfile = FileUtils.multipartFileToFile(file);
            //  File file = FileUtil.newFile(filePath);
            String sha256 = SecureUtil.sha256(mfile);

            HashMap<Object, Object> map = new HashMap<>();
            map.put("filename", mfile.getName());
            map.put("sha256", sha256);
            String body = JSONUtil.toJsonStr(map);

            logger.info("图片上传文件处理:"+body);

            Map<String, Object> result = WxPayApi.v3Upload(
                    WxDomain.CHINA.toString(),
                    WxApiType.MERCHANT_UPLOAD_MEDIA.toString(),
                    wxPayV3Bean.getMchId(),
                    getSerialNumber(),
                    wxPayV3Bean.getKeyPath(),
                    body,
                    mfile
            );
            // 根据证书序列号查询对应的证书来验证签名结果
            boolean verifySignature = WxPayKit.verifySignature(result, wxPayV3Bean.getPlatformCertPath());
            logger.info("签名验签结果verifySignature:" + verifySignature);
            //  JSONObject jsonObject=JSONUtil.parseObj(result.get("body"));
            if (MapUtil.getInt(result, "status")==200){
                JSONObject jsonObject=JSONUtil.parseObj(result.get("body"));
                String media_id = MapUtil.getStr(jsonObject,"media_id");
               // UploadMedia uploadMedia=new UploadMedia();
                litemallStorage.setMediaId(media_id);
                return  AjaxResult.success(litemallStorage);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error();
    }




    /**
     * 商户进件申请
     */


    @PostMapping("/applayment/add")
    public AjaxResult add(@RequestBody Map<String,Object> map)
    {

        try {

            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("文件上传失败!");
        }

    }


}
